/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <string.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */
GPIO_PinState state = GPIO_PIN_RESET;
uint8_t msg[64];
volatile uint8_t tx_done = 1;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
	if(huart == &huart2)
	{
		tx_done = 1;
	}
}
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	// 检验 帧头 长度 灯 亮灭
	if(huart == &huart2)
	{
		if(msg[0] == 0xAA)
		{
			if(msg[1] == Size)
			{
				uint8_t sum = 0;
				for(int i = 0;i < Size-1;i++)
				{
					sum += msg[i];
				}
				if(msg[Size-1] == sum)
				{
					GPIO_PinState st = GPIO_PIN_SET;
					for(int i = 2;i < Size-1;i+=2)
					{
						if(msg[i+1] == 0xFF) st = GPIO_PIN_SET;
						else st = GPIO_PIN_RESET;
						if(msg[i] == 0x01)
						{
							HAL_GPIO_WritePin(LED_RED_GPIO_Port, LED_RED_Pin, st);
						}
						else if(msg[i] == 0x02)
						{
							HAL_GPIO_WritePin(LED_GREEN_GPIO_Port, LED_GREEN_Pin, st);
						}
						else if(msg[i] == 0x03)
						{
							HAL_GPIO_WritePin(LED_BLUE_GPIO_Port, LED_BLUE_Pin, st);
						}
					}
				}
			}
		}
	}
	else return;
	HAL_UART_Transmit(&huart2,(uint8_t *) msg, Size,100);
	HAL_UARTEx_ReceiveToIdle_IT(&huart2,(uint8_t *) msg, 64);
}
//void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
//{
//	if(huart == &huart2)
//	{
//
//		if(msg[0] == 'R' && msg[2] == 'G' && msg[4] == 'B')
//		{
//			if(msg[0] == 'R')
//					{
//						GPIO_PinState st = GPIO_PIN_RESET;
//						if(msg[1] == '1')
//						{
//							st = GPIO_PIN_SET;
//						}
//						HAL_GPIO_WritePin(LED_RED_GPIO_Port, LED_RED_Pin, st);
//					}
//					if(msg[2] == 'G')
//					{
//						GPIO_PinState st = GPIO_PIN_RESET;
//						if(msg[3] == '1')
//						{
//							st = GPIO_PIN_SET;
//						}
//						HAL_GPIO_WritePin(LED_GREEN_GPIO_Port, LED_GREEN_Pin, st);
//					}
//					if(msg[4] == 'B')
//					{
//						GPIO_PinState st = GPIO_PIN_RESET;
//						if(msg[5] == '1')
//						{
//							st = GPIO_PIN_SET;
//						}
//						HAL_GPIO_WritePin(LED_BLUE_GPIO_Port, LED_BLUE_Pin, st);
//					}
//		}
//	}
//	HAL_UART_Receive_IT(&huart2, (uint8_t*)msg, 6);
//}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
  //HAL_UART_Receive_IT(&huart2, msg, 6);
  //HAL_UARTEx_ReceiveToIdle_IT(&huart2,(uint8_t*)msg, 64);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  /* ***************************************************************************************************
   * 基本要求：
   * -- 1.通过一个按键控制一红灯的开关；点击一次打开；第二次点击关闭；
   * DESIGN: 非中断实现——轮询
   * KEY1 读取电平 （本身硬件原因）
   *
   * -- 2.通过另外一个按键控制蓝色和绿色灯的闪烁；点击一次蓝灯闪烁，绿灯熄灭；再点击一次蓝灯熄灭，绿灯闪烁。
   * DESIGN: KEY2
   * 状态相反
   * ***************************************************************************************************
   */
  while (1)
  {
	  if(HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) == GPIO_PIN_RESET)
	  {

		  // 不按下 高 按下为 低
		  HAL_Delay(10);
		  if(HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) == GPIO_PIN_RESET)
			  HAL_GPIO_TogglePin(LED_RED_GPIO_Port,LED_RED_Pin);
		  while(HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) == GPIO_PIN_RESET){}
	  }

	  if(HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin) == GPIO_PIN_RESET)
	  {
		  HAL_Delay(10);
		  if(HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin) == GPIO_PIN_RESET)
		  {
			  HAL_GPIO_WritePin(LED_BLUE_GPIO_Port, LED_BLUE_Pin, state);
			  state = 1-state;
			  HAL_GPIO_WritePin(LED_GREEN_GPIO_Port, LED_GREEN_Pin, state);
		  }
		  while(HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin) == GPIO_PIN_RESET){}
	  }
//
//
//	  // 以上为轮询方式实现 。

	  /*
	   * ***************************************************************************************************
	   * 进阶要求：
	   * 1.串口可以接收到LED的工作状态，字符串含义自己确定；
	   * 2.使用串口发送命令来控制灯的开关和闪烁，字符串命令自己定义；
	   *
	   * DESIGN :
	   * 1）开启串口2
	   * 因为向串口发送信息在主循环里执行，所以使用中断有为了使数据不丢步。设置标识符。一旦发送完毕，在发送回调函数里进行修改。
	   *
	   * 2）串口发送命令。其本质流程是：
	   *  键盘-> 串口-> STM32 解析-> LED
	   *  使用 IT 接收定长数据 然后在RxCplt里分析数据。
	   *  如果想实现不定长 -> 串口的扩展函数
	   * ****************************************************************************************************
	   */

	  static uint32_t last_report = 0;
	      if (HAL_GetTick() - last_report >= 2000 && tx_done) {
	          last_report = HAL_GetTick();          // 更新时间戳

	          uint8_t r = HAL_GPIO_ReadPin(LED_RED_GPIO_Port,   LED_RED_Pin)   == GPIO_PIN_SET;
	          uint8_t g = HAL_GPIO_ReadPin(LED_GREEN_GPIO_Port, LED_GREEN_Pin) == GPIO_PIN_SET;
	          uint8_t b = HAL_GPIO_ReadPin(LED_BLUE_GPIO_Port,  LED_BLUE_Pin)  == GPIO_PIN_SET;

	          int len = snprintf(msg, sizeof(msg),
	                             "LED:红%s 绿%s 蓝%s \r\n",
	                             r?"亮":"灭", g?"亮":"灭", b?"亮":"灭"
	                             );

	          tx_done = 0;                           // 清标志
	          HAL_UART_Transmit_IT(&huart2, (uint8_t *)msg, len);
	      }

	  // 想要实现发完再发 标志位回调函数里再 设置
	  // 感觉无法接收我的逻辑 -- 关注发送串口信息的逻辑 ，降低频率 和 规定格式

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  /* USER CODE BEGIN MX_GPIO_Init_1 */

  /* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, LED_BLUE_Pin|LED_GREEN_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LED_RED_GPIO_Port, LED_RED_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pins : LED_BLUE_Pin LED_GREEN_Pin */
  GPIO_InitStruct.Pin = LED_BLUE_Pin|LED_GREEN_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pin : LED_RED_Pin */
  GPIO_InitStruct.Pin = LED_RED_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LED_RED_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : KEY1_Pin */
  GPIO_InitStruct.Pin = KEY1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(KEY1_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : KEY2_Pin */
  GPIO_InitStruct.Pin = KEY2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(KEY2_GPIO_Port, &GPIO_InitStruct);

  /* USER CODE BEGIN MX_GPIO_Init_2 */

  /* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
